<?php
/**
 * Created by PhpStorm.
 * User: season
 * Date: 2019/4/7
 * Time: 15:33
 */
declare(strict_types=1);
namespace App\Lib;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Token\Parser;
use Lcobucci\JWT\Validation\Constraint\IdentifiedBy;
use Lcobucci\JWT\Validation\Constraint\RelatedTo;
use Lcobucci\JWT\Validation\Validator;
use DateTimeImmutable;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use function random_bytes;

class JwtAuth
{
    static private $_config=[
        'audience' => 'http://127.0.0.1/token',//接收人
        'id' => 'Mr.WenShao',//token的唯一标识，这里只是一个简单示例
        'sign' => 'Mr.WenShao',//签名密钥
        'issuer' => 'Mr.WenShao',//签发人
        'expire' => 240 //有效期
    ];

    //生成token
    static public function getToken($k,$v, $timeStamp = null)
    {
        $now = new DateTimeImmutable();
        $config = Configuration::forSymmetricSigner(new Sha256(), InMemory::plainText(random_bytes(32)));
        $token = $config->builder()->issuedBy(self::$_config['issuer'])
            ->withHeader('iss', env('APP_URL'))
            ->permittedFor(env('APP_URL'))
            ->identifiedBy(self::$_config['id'])
            ->relatedTo(self::$_config['issuer'])
            ->issuedAt($now)
            ->canOnlyBeUsedAfter($now->modify('-1 minute'))
            ->expiresAt($now->modify('+'.self::$_config['expire'].' hour'))
            ->withClaim($k, $v)
            ->getToken($config->signer(), $config->signingKey());
        return $token->toString();
    }

    //验证token
    static public function verifyToken($token)
    {
        try{
            $parser = new Parser(new JoseEncoder());
            $validator = new Validator();
            $token = $parser->parse($token);
            if (! $validator->validate($token, new IdentifiedBy(self::$_config['id']), new RelatedTo(self::$_config['issuer']))) {
                return false;
            }
            return true;
        }catch (\Exception $e){
            _logger_(__file__, __line__, $e->getMessage());
            return false;
        }
    }

    //从token中获取信息
    static public function getUserId($token,$k)
    {
        try{
            $parser = new Parser(new JoseEncoder());
            $token = $parser->parse($token);
            return $token->claims()->get($k);
        }catch (\Exception $e){
            _logger_(__file__, __line__, $e->getMessage());
            return 0;
        }
    }
}
